from PySide6.QtWidgets import (QWidget, QHBoxLayout, QTableWidget, QComboBox,
                               QPushButton, QHeaderView, QMessageBox, QTableWidgetItem)
from PySide6.QtCore import Signal
from .extended_combobox import ExtendedComboBox

class BMSTable(QTableWidget):
    """指标配置表格"""
    bms_names = Signal(list)

    def __init__(self, parent=None):
        super().__init__(0, 3, parent)  # 初始0行，3列
        self.init_ui()
        
    def init_ui(self):
        # 设置表头
        headers = ["目标信号名", "数据表格列名", "操作"]
        self.setHorizontalHeaderLabels(headers)

        # 设置列宽
        header = self.horizontalHeader()
        header.setSectionResizeMode(0, QHeaderView.Stretch)
        header.setSectionResizeMode(1, QHeaderView.Stretch)
        header.setSectionResizeMode(2, QHeaderView.Stretch)

        self.cellChanged.connect(self.update_target_signals)

    def get_csv_columns(self):
        combobox = self.cellWidget(0, 1)
        items2 = []
        if combobox:
            model = combobox.model()
            for i in range(model.rowCount()):
                # 获取第i行第0列的文本数据
                items2.append(model.data(model.index(i, 0)))
        return items2

    def init_from_config(self, config: dict):
        """根据配置文件初始化表格"""
        items2 = self.get_csv_columns()
        self.setRowCount(0)
        for bms_name, column_name in config.items():
            row = self.rowCount()
            self.insertRow(row)
            # bms信号名称
            item = QTableWidgetItem(bms_name)
            self.setItem(row, 0, item)
            # 实际的列名
            cycle_combo = ExtendedComboBox()
            cycle_combo.addItems(items2)
            cycle_combo.setCurrentText(column_name)
            self.setCellWidget(row, 1, cycle_combo)
    
            # 操作按钮
            btn_widget = QWidget()
            btn_layout = QHBoxLayout(btn_widget)
            
            add_btn = QPushButton("增加")
            add_btn.clicked.connect(self.add_row)
            
            delete_btn = QPushButton("删除")
            delete_btn.clicked.connect(self.delete_row)  # 注意闭包传参
            
            btn_layout.addWidget(add_btn)
            btn_layout.addWidget(delete_btn)
            self.setCellWidget(row, 2, btn_widget)
            self.resizeRowToContents(row)

    def add_row(self):
        """添加一行新的指标配置"""
        button = self.sender()
        if not button:
            return
        # 找到按钮所在的部件
        widget = button.parent()
        if not widget:
            return
        # 获取部件所在的单元格位置
        row = self.indexAt(widget.pos()).row()
        self.insertRow(row + 1)
        row = row + 1
        
        # 小循环序号
        cycle_combo = ExtendedComboBox()
        self.setCellWidget(row, 1, cycle_combo)

        # 操作按钮
        btn_widget = QWidget()
        btn_layout = QHBoxLayout(btn_widget)
        
        add_btn = QPushButton("增加")
        add_btn.clicked.connect(self.add_row)
        
        delete_btn = QPushButton("删除")
        delete_btn.clicked.connect(self.delete_row)
        
        btn_layout.addWidget(add_btn)
        btn_layout.addWidget(delete_btn)
        self.setCellWidget(row, 2, btn_widget)
        
        # 自动调整行高
        self.resizeRowToContents(row)
        
    def delete_row(self):
        """删除指定行"""
        button = self.sender()
        if not button:
            return
        # 找到按钮所在的部件
        widget = button.parent()
        if not widget:
            return
        # 获取部件所在的单元格位置
        row = self.indexAt(widget.pos()).row()

        if row < 1:
            QMessageBox.information(self, "提示", "至少保留一行指标配置")
            return
            
        self.removeRow(row)
        self.update_target_signals()
        
    def get_all_configs(self):
        """获取所有指标的配置信息，返回字典{第一列文本: 第二列下拉框当前文本}"""
        configs = {}
        row_count = self.rowCount()
        
        for row in range(row_count):
            # 获取第一列的文本项
            item = self.item(row, 0)
            # 获取第二列的下拉框组件
            combo_box = self.cellWidget(row, 1)  # 这里修复为cellWidget
            
            # 验证获取到的对象
            if item is not None and combo_box is not None:
                key = item.text().strip()
                value = combo_box.currentText().strip()

                # 只添加非空键
                if key:
                    configs[key] = value       
        return configs

    def update_target_signals(self):
        """从表格中提取“目标信号名”，更新原始信号列表"""
        target_signals = []
        # 遍历表格所有行，获取第一列（目标信号名）的内容
        for row in range(self.rowCount()):
            item = self.item(row, 0)
            if item and item.text().strip():
                target_signals.append(item.text().strip())
        self.bms_names.emit(target_signals)
